import asyncio
from lib.sensors import ws2812
from lib.mqtt.index import client
from lib.config.index import mqtt_config
from lib.clock import ticker_clock
from utils.common import integerToRGB
import json
import sys

__service__ = "ws2812_mqtt_manager"
__description__ = "manage ws2812 effect"

_ws2812 = None
keep_alive = max(mqtt_config.get_keepalive() / 2, 10)  # 最小10S ping
timer = ticker_clock.TickerClock(keep_alive * 1000)
is_debug = mqtt_config.is_debug()

config = {
    "light_num": 30,
    "brightness": 100,
    "enable": 0,
    "rgbColor": 16711680,
    "pin": 1
}

def on_message(topic, msg):
    global _ws2812,config
    #print("接收到订阅消息: ", topic, msg)
    data = msg.decode("utf-8")
    json_data = json.loads(data)
    try:
        update_config(json_data)
    except Exception as e:
       sys.print_exception(e)

def update_config(json_data):
    global config,_ws2812
    if "type" in json_data:
        type = json_data["type"]
        if type == "set_config":
            key = json_data["key"]
            config[key] = json_data["value"]
            if _ws2812:
                _ws2812.clear()
            #print(config)
            _ws2812 = ws2812.WS2812(config["pin"], int(config["light_num"]))
            update_ws2812()
                
        if type == "set_state":
            key = json_data["key"]
            config[key] = json_data["value"]
            update_ws2812()

def init():
    print("ws2812 mqtt manager service started")
    client.set_callback(on_message)
    client.connect()
    client.subscribe()
    

def update_ws2812():
    global _ws2812,config
    #print("update ws2812 state")
    if not _ws2812:
        _ws2812 = ws2812.WS2812(config["pin"], int(config["light_num"]))
    if config["enable"] == 0:
        _ws2812.clear()
        print("disable ws2812 state")
        return
    print("enable ws2812 state", config)
    _ws2812.setBrightness(config["brightness"])
    _ws2812.fill(integerToRGB(config["rgbColor"]))
    

def keepalive_timer():
    if is_debug:
        print("mqtt ping diff: ", timer.get_diff())
    if timer.check():
        if is_debug:
            print("mqtt publish ping")
        client.ping()


async def run():
    global _ws2812,config

    while True:
        keepalive_timer()
        await client.wait_msg()
        await asyncio.sleep(1)
        
if __name__ == "__main__":
    _ws2812 = ws2812.WS2812(config["pin"], int(config["light_num"]))
    _ws2812.clear()

